package com.lx.web.servlet;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.lx.bean.ResultInfo;
import com.lx.bean.User;
import com.lx.email.MailUtil;
import com.lx.service.UserService;
import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.mail.MessagingException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
//    @Autowired
//    ForumService forumService;


    @ResponseBody
    @RequestMapping("/getImg")
    public void getImg(HttpServletRequest req, HttpServletResponse response) {
        BufferedImage bi = new BufferedImage(200, 80, BufferedImage.TYPE_INT_RGB);
        Graphics2D gra = bi.createGraphics();
        gra.setColor(Color.black);
        gra.fillRect(0, 0, 200, 100);
        Random random = new Random();
        gra.setColor(Color.red);
        gra.setFont(new Font("华文行楷", Font.ITALIC | Font.BOLD, 70));
        List<Integer> rand = new ArrayList<>();
        rand.clear();
        for (int i = 0; i <= 3; i++) {
            int i1 = random.nextInt(10);
            rand.add(i1);
            gra.drawString(i1 + "", i * 50, 60 + (random.nextInt(31) - 10));
        }

        HttpSession session = req.getSession();
        StringBuilder sb = new StringBuilder();
        for (Integer integer : rand) {
            sb.append(integer);
        }
        session.setAttribute("code", sb);
        System.out.println(sb);
        try {
            ServletOutputStream os = response.getOutputStream();
            ImageIO.write(bi, "JPEG", os);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("出错");
        }
    }


    @ResponseBody
    @RequestMapping("/getCode")
    public void getCode(HttpServletRequest req, HttpServletResponse response) {
        StringBuilder code = (StringBuilder) req.getSession().getAttribute("code");
        try {
            if (code != null) {
                req.setCharacterEncoding("utf-8");
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().write(code.toString());
            }
            //response.getWriter().write("ddddddddddddddddd");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 发送邮箱验证码
     *
     * @param code
     * @param recipients
     */
    @ResponseBody
    @RequestMapping("/sendEmail")
    public void sendEmail(String code, String recipients) {


        String message = "你好" + recipients + "！\n欢迎注册账户，请将验证码填写到注册页面。验证码：" + code + "";
        try {
            MailUtil.send_mail(recipients, message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        System.out.println("注册账户邮件发送成功!");

    }

    @ResponseBody
    @RequestMapping("/addUser")
    public String addUser(String username, String password, String email, String nickname) {
        String image = "https://songtell-1251684550.cos.ap-chengdu.myqcloud.com/news/QWTRUWIPhoto.jpg";
        User user = new User(1, username, password, email, nickname, image);
        int i = userService.insertUser(user);
        System.out.println(i + "");
        return i + "";
    }


    @ResponseBody
    @RequestMapping("/selAll")
    public String selAll() {
        return userService.selAll().toString();
    }


    @ResponseBody
    @RequestMapping("/loginByName")
    public ResultInfo selById(HttpServletResponse response, HttpSession session, String username, String password) {
        ResultInfo info = new ResultInfo();
        User login = userService.login(username, password);
        if (login == null) {
            info.setFlag(false);
            info.setErrorMsg("用户名或密码错误");
        } else {
//            登录成功
            Cookie cookie = new Cookie("username", username);
            Cookie cookie3 = new Cookie("userimage", login.getImage());
            Cookie cookie2 = new Cookie("userid", login.getuId() + "");
            cookie.setPath("/");
            cookie2.setPath("/");
            cookie3.setPath("/");
            response.addCookie(cookie);
            response.addCookie(cookie2);
            response.addCookie(cookie3);
            login.setPassword("");
            session.setAttribute(login.getUsername(), login);
            info.setFlag(true);
            info.setData(login);
        }
        return info;
    }

    @ResponseBody
    @RequestMapping("/verifyEmail")
    public String verifyEmail(String email) {
        List<User> users = userService.selAll();
        for (User user : users) {
            if (user.getEmail().equals(email)) {
                return user.toString();
            }
        }
        return "";
    }

    @RequestMapping("/finduser")
    @ResponseBody
    public ResultInfo finduser(HttpSession session, HttpServletResponse response, @CookieValue(value = "username", required = false) String username) throws IOException {
        ResultInfo info = new ResultInfo();
        if (username != null && !"".equals(username)) {
            User user = (User) session.getAttribute(username);
            if (user == null) {
//           "用户没有登录"
                info.setFlag(false);
                info.setErrorMsg("用户没有登录");
                Cookie cookie = new Cookie("username", null);//cookie名字要相同
                cookie.setMaxAge(0); //
                cookie.setPath("/");  // 相同路径
                Cookie cookie1 = new Cookie("userid", null);//cookie名字要相同
                cookie1.setMaxAge(0); //
                cookie1.setPath("/");  // 相同路径
                 Cookie cookie2 = new Cookie("userimage", null);//cookie名字要相同
                cookie2.setMaxAge(0); //
                cookie2.setPath("/");  // 相同路径
                response.addCookie(cookie);
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            } else {

                info.setData(user);
                info.setFlag(true);
            }
        } else {
            Cookie cookie = new Cookie("username", null);//cookie名字要相同
            cookie.setMaxAge(0); //
            cookie.setPath("/");  // 相同路径
            Cookie cookie1 = new Cookie("userid", null);//cookie名字要相同
            cookie1.setMaxAge(0); //
            cookie1.setPath("/");  // 相同路径
            response.addCookie(cookie);
            response.addCookie(cookie1);
            info.setFlag(false);
            info.setErrorMsg("用户没有登录");
        }
        return info;
    }


    @RequestMapping("/quituser")
    @ResponseBody
    public ResultInfo quituser(HttpSession session, @CookieValue(value = "username", required = false) String username) throws IOException {
        ResultInfo info = new ResultInfo();

        if (username != null && !"".equals(username)) {
            session.removeAttribute(username);

        }

        return info;
    }


}
